package com.baixun.gassystem.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baixun.gascommon.config.ApiConfig;
import com.baixun.gascommon.utils.HttpClientUtil;
import com.baixun.gascommon.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.*;

/**
 * @program: 上海燃气驾驶舱
 * @description: 讲用户信息下载到sys_user
 * @author: yesong
 **/
@Service
public class UserDataService {

    @Autowired
    private ApiService apiService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private SysUserService sysUserService;

    private static final String TOKEN_KEY = "SAAS_SESSION_TOKEN";


    // 此接口不再使用 直接使用evs的获取信息
    private static Connection getDatabaseConnection() throws SQLException {
        String url = "jdbc:mysql://gz-cdb-a1k9mjhj.sql.tencentcdb.com:29414/shanghai-gas";
        String user = "root";
        String password = "clRDS@1010&&";
        return DriverManager.getConnection(url, user, password);
    }

    @Scheduled(fixedRate = 86400000) // 每24小时执行一次
    public void fetchAndSaveUsers() throws Exception {
        // 1. 获取并解析用户数据
        List<JSONObject> users = fetchUserData();

        // 2. 将用户数据保存到数据库
        saveUsersToDatabase(users);
    }

    // 从第三方接口获取用户数据
    private List<JSONObject> fetchUserData() throws Exception {
        List response = apiService.getUsersFromAllDepartments();

        // 将 response 转换为 JSON 数组
        JSONArray dataArray = JSON.parseArray(response.toString());

        // 从 Redis 获取 token
        String token = redisUtils.get(TOKEN_KEY);
        if (token == null) {
            throw new Exception("No valid token found in Redis.");
        }

        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie", "SAAS_SESSION=" + token);
        headers.put("Content-Type", "application/json; charset=UTF-8");

        List<JSONObject> userDetailsList = new ArrayList<>();

        // 遍历每个用户的 user_id 并获取详细信息
        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject userObject = dataArray.getJSONObject(i);
            String userId = userObject.getString("userId");
            String url = ApiConfig.DOMAIN + ApiConfig.USERS_API + userId;
            String responseString = HttpClientUtil.sendGetRequest(url, headers);
            JSONObject userDetail = JSON.parseObject(responseString);
            userDetailsList.add(userDetail);
        }
        return userDetailsList;

    }

    // 将用户数据保存到数据库
    private void saveUsersToDatabase(List<JSONObject> users) throws Exception {
        if (users == null || users.isEmpty()) {
            throw new Exception("User list is null or empty, cannot save to database.");
        }

        Connection connection = getDatabaseConnection();
        if (connection == null) {
            throw new Exception("Failed to establish a database connection.");
        }

        String insertSql = "INSERT INTO sys_user (id, user_name, pass_word, create_time, status, tel, salt, deleted, password_status) "
                + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        String checkSql = "SELECT COUNT(*) FROM sys_user WHERE id = ?";

        // 使用 Set 来记录已经处理过的用户 ID，避免重复
        Set<Long> processedIds = new HashSet<>();

        try (PreparedStatement insertStmt = connection.prepareStatement(insertSql);
             PreparedStatement checkStmt = connection.prepareStatement(checkSql)) {

            for (JSONObject user : users) {
                if (user == null) continue;

                Long id = user.getLong("id");

                // 如果 ID 已经处理过，则跳过
                if (processedIds.contains(id)) {
                    System.out.println("User with ID " + id + " already processed. Skipping.");
                    continue;
                }

                String userName = user.getString("name");
                String rawPassword = "123456";
                String passWord = sysUserService.Md5Password(rawPassword).getData().toString();
                Timestamp createTime = new Timestamp(System.currentTimeMillis());
                String status = user.getString("status");
                String tel = user.getString("tel");
                String salt = "abc";
                int deleted = 0;
                String passwordStatus = user.getString("passwordStatus");

                // 检查 ID 是否已存在
                checkStmt.setLong(1, id);
                try (ResultSet resultSet = checkStmt.executeQuery()) {
                    if (resultSet.next() && resultSet.getInt(1) > 0) {
                        System.out.println("User with ID " + id + " already exists in database. Skipping insertion.");
                        processedIds.add(id); // 记录已经处理过的 ID
                        continue; // 如果 ID 已存在，跳过该条记录
                    }
                }

                // 设置插入语句的参数
                insertStmt.setLong(1, id);
                insertStmt.setString(2, userName);
                insertStmt.setString(3, passWord);
                insertStmt.setTimestamp(4, createTime);
                insertStmt.setString(5, status);
                insertStmt.setString(6, tel);
                insertStmt.setString(7, salt);
                insertStmt.setInt(8, deleted);
                insertStmt.setString(9, passwordStatus);

                // 添加到批处理中
                insertStmt.addBatch();

                // 记录已经处理过的 ID
                processedIds.add(id);
            }

            // 执行批量插入
            insertStmt.executeBatch();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new Exception("Error while inserting users data into sys_user table.", e);
        } finally {
            // 确保连接关闭
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
